<?php

class Retailer_Backend_Adminhtml_AccountController extends Mage_Adminhtml_Controller_action
{

    protected function _initAction() {
            $this->loadLayout()
                    ->_setActiveMenu('backend/account')
                    ->_addBreadcrumb(Mage::helper('adminhtml')->__('Account Manager'), Mage::helper('adminhtml')->__('Account Manager'));

            return $this;
    }

    public function indexAction() {
            
            $user = Mage::getSingleton('admin/session')->getUser();
            if($user->getRole()->getRoleName()!="Administrators"){
                $model  = Mage::getModel('admin/user')->load($user->getId());

                if ($model->getId() || $id == 0) {
                        $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
                        if (!empty($data)) {
                                $model->setData($data);
                        }

                        Mage::register('backend_data', $model);

                        $this->loadLayout();
                        $this->_setActiveMenu('backend/account');

                        $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Product Manager'), Mage::helper('adminhtml')->__('Product Manager'));
                        $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Product News'), Mage::helper('adminhtml')->__('Product News'));

                        $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

                        $this->_addContent($this->getLayout()->createBlock('backend/adminhtml_account_edit'))
                                ->_addLeft($this->getLayout()->createBlock('backend/adminhtml_account_edit_tabs'));

                        $this->renderLayout();
                } else {
                        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('backend')->__('Product does not exist'));
                        $this->_redirect('*/*/');
                }
            }
            else{
                $this->_initAction()
                    ->renderLayout();
            }
    }

    public function editAction() {
            $id     = $this->getRequest()->getParam('id');
            $model  = Mage::getModel('admin/user')->load($id);

            if ($model->getId() || $id == 0) {
                    $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
                    if (!empty($data)) {
                            $model->setData($data);
                    }

                    Mage::register('backend_data', $model);

                    $this->loadLayout();
                    $this->_setActiveMenu('backend/account');

                    $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Product Manager'), Mage::helper('adminhtml')->__('Product Manager'));
                    $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Product News'), Mage::helper('adminhtml')->__('Product News'));

                    $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

                    $this->_addContent($this->getLayout()->createBlock('backend/adminhtml_account_edit'))
                            ->_addLeft($this->getLayout()->createBlock('backend/adminhtml_account_edit_tabs'));

                    $this->renderLayout();
            } else {
                    Mage::getSingleton('adminhtml/session')->addError(Mage::helper('backend')->__('Product does not exist'));
                    $this->_redirect('*/*/');
            }
    }

    public function newAction() {
            $id     = $this->getRequest()->getParam('id');
            $model  = Mage::getModel('admin/user')->load($id);

            if ($model->getId() || $id == 0) {
                    $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
                    if (!empty($data)) {
                            $model->setData($data);
                    }

                    Mage::register('backend_data', $model);

                    $this->loadLayout();
                    $this->_setActiveMenu('backend/account');

                    $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Product Manager'), Mage::helper('adminhtml')->__('Product Manager'));
                    $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Product News'), Mage::helper('adminhtml')->__('Product News'));

                    $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

                    $this->_addContent($this->getLayout()->createBlock('backend/adminhtml_account_edit'))
                            ->_addLeft($this->getLayout()->createBlock('backend/adminhtml_account_edit_add'));

                    $this->renderLayout();
            } else {
                    Mage::getSingleton('adminhtml/session')->addError(Mage::helper('backend')->__('Product does not exist'));
                    $this->_redirect('*/*/');
            }
    }

    public function saveAction() {

        $data = $this->getRequest()->getPost();
        $id = $this->getRequest()->getParam('id');
        $fail=false;
            if ($data ) {
                if(!isset($data['username'])){//&& $data['newpassword']===$data['confirmp'] && $data['newemail']===$data['confirme']){
                    
//                    //this way the name is saved in DB
//                            $data['filename'] = $_FILES['filename']['name'];
//                    }
                    $user = Mage::getSingleton('admin/session')->getUser();
                    $link = Mage::getModel('backend/backend')->load($user->getUserId(),'user_id');
                    $model = Mage::getModel('admin/user')->load($id);
                    $mod = Mage::getModel('backend/backend')->load($id,'user_id');

                    if($user->getRole()->getRoleName()=="Administrators"&&isset($data['store_id'])&&$data['store_id']!=0){
                        //$model2->setData('user_id', $model->getId());
                        //$mod->load($id,'user_id');
                        $mod//->setId($this->getRequest()->getParam('id'))
                            ->setData('store_id',$data['store_id']);

                            //->setData('commission',$data['commission'])
                            //->setData('filename_logo',"nothing");
                        $mod->setData('user_id',$id);
                        //if(!$fail){
                        $mod->save();
                        //}
                        $link->load($mod->getId());
                    }
                    else{
                        $model=$user;
                    }


                    $fail = false;
                    

                    
                    if(!$fail){
                        $usave = Mage::getModel('admin/user')
                            ->setId($id)
                            ->setUsername($data['username1'])
                            ->setData('firstname',$data['firstname'])
                            ->setData('lastname',$data['lastname'])
                        //if(isset($data['newemail'])&&$data['newemail']!=''){
                            ->setData('email',$data['email']);
                        //}
                        if($this->getRequest()->getParam('newpassword', false)){//&&strlen($data['newpassword'])>=7){
                            $usave->setPassword($this->getRequest()->getParam('newpassword', false));
                        }
                        try {
                            try {
                                $_isValid = Zend_Validate::is($usave->getUsername(), 'NotEmpty')
                                    && Zend_Validate::is($usave->getFirstname(), 'NotEmpty')
                                    && Zend_Validate::is($usave->getLastname(), 'NotEmpty')
                                    && Zend_Validate::is($usave->getEmail(), 'EmailAddress');

                                if (!$_isValid) {
                                    Mage::throwException(Mage::helper('adminhtml')->__('Error while saving account. Please check all required fields'));
                                }
                                if ($usave->userExists()) {
                                    Mage::throwException(Mage::helper('adminhtml')->__('User with the same User Name or Email aleady exists'));
                                }
                                $usave->save();
                                //Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Account successfully saved'));
                            }
                            catch (Mage_Core_Exception $e) {
                                throw $e;
                            }
                            catch (Exception $e) {
                                throw new Exception(Mage::helper('adminhtml')->__('Error while saving account. Please try again later'));
                            }
                        }
                        catch (Exception $e) {
                            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                        }

                        //$model->save();
                    }
                    
                    
                    //$model->setId($this->getRequest()->getParam('id'));
                    //$user = Mage::getModel('admin/user');
                    
                    
                    $store = Mage::getModel('core/store')->load($link->getStoreId());
                    if(isset($data['spawn'])){

                        $cus = Mage::getModel('customer/customer');//->load($this->getRequest()->getParam('id'));
                        //$model->setWebsiteId($link->getStoreId());//->loadByEmail($data['email']);
                        //$model->load($id);
                        //$model->setId('1');
                        $cus->setData('website_id',$link->getStoreId());
                        $cus->setStore($store);
                        $cus->setData('firstname',$user->getFirstname());
                        $cus->setData('lastname',$user->getLastname());
                        $cus->setData('group_id',1);
                        $cus->setData('email',$user->getEmail());
                        //if(isset($data['password'])){
                            $cus->setPassword("temppass1");
                        //}
                        if(!$fail){
                        $cus->save();
                        }
                        //if(isset($data['set_link'])){// && $data['set_link']=="yes"){
                            $link->setCustomerId($cus->getId());
                            if(!$fail){
                            $link->save();
                            }
                        //}


                    }
                    for($i=0;$i<$data['addr_count'];$i++){
                    if((isset($data["addr_street_$i"])&&$data["addr_street_$i"]!="")||isset($data["delete_$i"])){
                        if(!isset($data["entity_id_$i"])){
                            $data["entity_id_$i"]=null;
                        }

                        $address = Mage::getModel('customer/address')->load($data["entity_id_$i"])
                                ->setData('firstname',$data["addr_fname_$i"])
                                ->setData('lastname',$data["addr_lname_$i"])
                                ->setData('street',$data["addr_street_$i"])
                                ->setData('city',$data["addr_city_$i"])
                                ->setData('postcode',$data["addr_postcode_$i"])
                                ->setData('region',$data["addr_region_$i"])
                                //->setData('country_id',$data['country_id'])
                                ->setData('telephone',$data["addr_telephone_$i"])
                                ->setData('fax',$data["addr_fax_$i"])
                                ->setCustomerId($link->getCustomerId());
                                //->setIsDefaultBilling(true)
                                //->setIsDefaultShipping(true);

//                        if(!isset($data['entity_id'])){
                           
//                            $customer->addAddress($address);
//                            $customer->save();
//
//                        }
                        //$address
                       if(!$fail){
                           
                            $address->save();
                       }
                       if(isset($data["delete_$i"])){
                            $address->delete();
                           }
                    }
                    }
                }
                else{
                    $usern = Mage::getModel('admin/user')->load($id);
                    $usern->setUsername($data['username'])
                        //->setFirstname($data['firstname'])
                        //->setLastname($data['lastname'])
                        //->setRole($data['role'])
                        ->setEmail(strtolower($data['email']));
                        if ( $data['password']&& $data['password'] == $data['cpassword'] ) {
                            $usern->setPassword($data['password']);
                        }
                        else{
                            $fail=true;
                        }

                    if(!$fail){
                        $usern->save();
                        $role = Mage::getModel('admin/role')
                            ->setParentId($data['role'])
                            ->setTreeLevel(2)
                            ->setRoleType("U")
                            ->setUserId($usern->getId())
                            ->save();
                        
                        $linkn = Mage::getModel('backend/backend')->load($id);
                        $linkn->setUserId($usern->getId())
                              ->setStoreId($data['site'])
                              ->save();
                        $storen = Mage::getModel('core/store')->load($linkn->getStoreId());
                        $cusn = Mage::getModel('customer/customer');//->load($this->getRequest()->getParam('id'));
                        //$model->setWebsiteId($link->getStoreId());//->loadByEmail($data['email']);
                        //$model->load($id);
                        //$model->setId('1');
                        $cusn->setData('website_id',$linkn->getStoreId());
                        $cusn->setStore($storen);
                        $cusn->setData('firstname',$usern->getFirstname());
                        $cusn->setData('lastname',$usern->getLastname());
                        $cusn->setData('group_id',1);
                        $cusn->setData('email',$usern->getEmail());
                        //if(isset($data['password'])){
                            $cusn->setPassword("temppass1");
                        //}
                        if(!$fail){
                        $cusn->save();
                        }
                        //if(isset($data['set_link'])){// && $data['set_link']=="yes"){
                            $linkn->setCustomerId($cusn->getId());
                            if(!$fail){
                            $linkn->save();
                            }
                        //}



                    }
                }
                    try {
//                            if ($model->getCreatedAt() == NULL || $model->getUpdatedAt() == NULL) {
//                                    $model->setCreatedAt(now())
//                                            ->setUpdatedAt(now());
//                            } else {
//                                    $model->setUpdatedAt(now());
//                            }
//                            echo "1";
                            
                            
                            //$model->save();
//                            echo "2";
                            //$test = Mage::getModel('backend/backend')->load($id);
                            if(!$fail){
                                //$usern->save();

                            Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('backend')->__("Item was successfully saved"));
                            Mage::getSingleton('adminhtml/session')->setFormData(false);
                            }
                            if ($this->getRequest()->getParam('back')) {
                                    $this->_redirect('*/*/edit', array('id' => $model->getId()));
                                    return;
                            }
                            $this->_redirect('*/*/');
                            return;
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            Mage::getSingleton('adminhtml/session')->setFormData($data);
            $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            return;
        }
    }
    Mage::getSingleton('adminhtml/session')->addError(Mage::helper('backend')->__('Error--Make sure that you typed your email and password correctly!'));
    $this->_redirect('*/*/');
    }

    public function deleteAction() {
            if( $this->getRequest()->getParam('id') > 0 ) {
                    try {
                            $model = Mage::getModel('backend/backend');

                            $model->setId($this->getRequest()->getParam('id'))
                                    ->delete();

                            Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
                            $this->_redirect('*/*/');
                    } catch (Exception $e) {
                            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                            $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                    }
            }
            $this->_redirect('*/*/');
    }

public function massDeleteAction() {
    $backendIds = $this->getRequest()->getParam('backend');
    if(!is_array($backendIds)) {
                    Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
    } else {
        try {
            foreach ($backendIds as $backendId) {
                $backend = Mage::getModel('backend/backend')->load($backendId);
                $backend->delete();
            }
            Mage::getSingleton('adminhtml/session')->addSuccess(
                Mage::helper('adminhtml')->__(
                    'Total of %d record(s) were successfully deleted', count($backendIds)
                )
            );
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
        }
    }
    $this->_redirect('*/*/index');
}

public function massStatusAction()
{
    $backendIds = $this->getRequest()->getParam('backend');
    if(!is_array($backendIds)) {
        Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
    } else {
        try {
            foreach ($backendIds as $backendId) {
                $backend = Mage::getSingleton('backend/backend')
                    ->load($backendId)
                    ->setStatus($this->getRequest()->getParam('status'))
                    ->setIsMassupdate(true)
                    ->save();
            }
            $this->_getSession()->addSuccess(
                $this->__('Total of %d record(s) were successfully updated', count($backendIds))
            );
        } catch (Exception $e) {
            $this->_getSession()->addError($e->getMessage());
        }
    }
    $this->_redirect('*/*/index');
}

public function exportCsvAction()
{
    $fileName   = 'backend.csv';
    $content    = $this->getLayout()->createBlock('backend/adminhtml_customers_grid')
        ->getCsv();

    $this->_sendUploadResponse($fileName, $content);
}

public function exportXmlAction()
{
    $fileName   = 'backend.xml';
    $content    = $this->getLayout()->createBlock('backend/adminhtml_customers_grid')
        ->getXml();

    $this->_sendUploadResponse($fileName, $content);
}

protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
{
    $response = $this->getResponse();
    $response->setHeader('HTTP/1.1 200 OK','');
    $response->setHeader('Pragma', 'public', true);
    $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
    $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
    $response->setHeader('Last-Modified', date('r'));
    $response->setHeader('Accept-Ranges', 'bytes');
    $response->setHeader('Content-Length', strlen($content));
    $response->setHeader('Content-type', $contentType);
    $response->setBody($content);
    $response->sendResponse();
    die;
}
}